package com.jh.paymentchannel.service;

import com.jh.paymentchannel.util.Util;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import static java.nio.charset.StandardCharsets.UTF_8;


@Controller
public class KJCallBackService {

    private static final Logger log = LoggerFactory.getLogger(KJCallBackService.class);

    private final Util util;
    private final RestTemplate restTemplate;

    @Autowired
    public KJCallBackService(Util util, RestTemplate restTemplate) {
        this.util = util;
        this.restTemplate = restTemplate;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/kj/notify_call")
    public @ResponseBody
    void notifycall(HttpServletRequest request, HttpServletResponse response) throws IOException {
        InputStream inputStream = request.getInputStream();
        ByteArrayOutputStream byteArray;
        byteArray = new ByteArrayOutputStream();
        byte[] dat = new byte[2048];
        int byteLen;
        while ((byteLen = inputStream.read(dat, 0, 2048)) != -1) {
            byteArray.write(dat, 0, byteLen);
        }
        byteArray.flush();
        String info = new String(byteArray.toByteArray(), UTF_8);
        JSONObject jsonInfo = JSONObject.fromObject(info);
        inputStream.close();
        byteArray.close();
        HashMap<String, Object> resData = new HashMap<>();
        String resString;
        Object msg = jsonInfo.get("msg");
        Object code = jsonInfo.get("code");
        jsonInfo = JSONObject.fromObject(msg);
        if ("0000".equals(code.toString())) {
            try {
                //log.info("验签前");
                //验签,不抛异常表示验签成功
                //data =(HashMap) Plat2Mer_v40.getPlatNotifyData(request);
                //log.info("验签成功=============== "+data==null?null:data.toString());
                //验签成功 ，
                //resData.put("outTradeNo", data.get("outTradeNo"));
                //resData.put("orderNo", data.get("orderNo"));
                //resData.put("errMsg", data.get("errMsg"));
                //String errMsg = request.getParameter("errMsg");
                resData.put("orderNo", jsonInfo.getString("orderNo"));
                resData.put("transAmount", jsonInfo.getString("transAmount"));
                resData.put("payStatus", jsonInfo.getString("payStatus"));
                resData.put("setStatus", jsonInfo.getString("setStatus"));
                resData.put("amount", jsonInfo.getString("amount"));
                resData.put("rate", jsonInfo.getString("rate"));
                resData.put("fee", jsonInfo.getString("fee"));
                resData.put("outTradeNo", jsonInfo.getString("outTradeNo"));
                resData.put("sign", jsonInfo.getString("sign"));
                log.info("resData====" + resData.toString());
                //resString = Mer2Plat_v40.merNotifyResData(resData);
                //log.info("resString===="+resString.toString());
                //商户可加入自己的处理逻辑
                /* 更新订单状态*/
                /* 调用下单，需要得到用户的订单信息*/

                /* 根据的用户手机号码查询用户的基本信息*/
                MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
                requestEntity.add("status", "1");
                requestEntity.add("third_code", jsonInfo.getString("orderNo"));
                requestEntity.add("order_code", jsonInfo.getString("outTradeNo"));

                /* 判断是否有外放的通道的处理， 如果有那么继续回调外放哦*/
                URI uri = util.getServiceUrl("transactionclear", "error url request!");
                String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";


                requestEntity = new LinkedMultiValueMap<>();
                requestEntity.add("order_code", jsonInfo.getString("outTradeNo"));
                String result = restTemplate.postForObject(url, requestEntity, String.class);

                JSONObject jsonObject = JSONObject.fromObject(result);
                JSONObject resultObj = jsonObject.getJSONObject("result");
                String outMerOrdercode = resultObj.getString("outMerOrdercode");
                String orderdesc = resultObj.getString("desc");
                String phone = resultObj.getString("phone");
                String tranamount = resultObj.getString("amount");
                String channelTag = resultObj.getString("channelTag");
                String notifyURL = resultObj.getString("outNotifyUrl");
                if (outMerOrdercode != null && !outMerOrdercode.equalsIgnoreCase("")) {
                    uri = util.getServiceUrl("channel", "error url request!");
                    url = uri.toString() + "/v1.0/channel/callback/yilian/notify_call";
                    requestEntity = new LinkedMultiValueMap<>();
                    requestEntity.add("merchant_no", phone);
                    requestEntity.add("amount", tranamount);
                    requestEntity.add("channel_tag", channelTag);
                    requestEntity.add("order_desc", URLEncoder.encode(orderdesc, "UTF-8"));
                    requestEntity.add("order_code", outMerOrdercode);
                    requestEntity.add("sys_order", jsonInfo.getString("outTradeNo"));
                    requestEntity.add("notify_url", URLEncoder.encode(notifyURL, "UTF-8"));
                    restTemplate.postForObject(url, requestEntity, String.class);
                }
                resString = "success";

            } catch (Exception e) {
                //如果验签失败，则抛出异常，返回ret_code=1111
                log.info("验证签名发生异常" + e);
                resString = "fail";
            }
        } else {
            log.info("验证签名发生异常" + jsonInfo.getString("errMsg"));
            resString = "fail";
        }
        PrintWriter write = response.getWriter();
        write.print(resString);
        write.flush();

    }

    @RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/kj/ret_url")
    public String retcall(HttpServletRequest request) {
        Map<String, String[]> data = request.getParameterMap();
        String merchantNo = request.getParameter("merchantNo");
        // TODO: 功能未完成

        return "redirect:http://1.xinli2017.applinzi.com/login/zhufucg.html";
    }


}
